package com.ciwong.epaper.modules.me.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.NoConnectionError;
import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.bean.UserAccountInfo;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.me.util.MeUtil;
import com.ciwong.epaper.util.AESCBCUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.weakpassword.CheckPWD;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.widget.CWDialog;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by young on 2016/6/21.
 * 重置密码
 */
public class ResetPasswordActivity extends BaseActivity {
    private EditText reset_psw__pass, reset_psw_pass1;
    private Button reset_psw__step_btn;
    private String phoneNumber;
    private String verity_code, psw1, psw2;
    private TextView err_tips_tv;
    private final int TIPS_GONE = 1;
    private final int JIMPTOREGIST = 2;

    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case TIPS_GONE:
                    err_tips_tv.setVisibility(View.INVISIBLE);
                    break;
                case JIMPTOREGIST:
                    //重置密码成功会跳登陆界面
                    MeJumpManager.jumpToLogin2(ResetPasswordActivity.this, 0, phoneNumber, psw1, EConstants.LoginFrom.LOGIN_FROM_RESETPSW);
                    break;
            }
        }
    };

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.reset_psw__step_btn) {
                //重置密码
                resetpsw();
            }
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_reset_password;
    }

    @Override
    protected void findViews() {
        reset_psw__pass = (EditText) findViewById(R.id.reset_psw__pass);
        reset_psw_pass1 = (EditText) findViewById(R.id.reset_psw_pass1);
        reset_psw__step_btn = (Button) findViewById(R.id.reset_psw__step_btn);
        err_tips_tv = (TextView) findViewById(R.id.err_tips_tv);

    }

    @Override
    protected void initEvent() {
        reset_psw__step_btn.setOnClickListener(mOnClickListener);

    }

    @Override
    protected void init() {
        setTitleText(R.string.retpassword);
    }

    @Override
    protected void loadData() {
        Intent intent = getIntent();
        if (intent != null) {
            phoneNumber = intent.getStringExtra(IntentFlag.INTENT_FLAG_STR);
            verity_code = intent.getStringExtra(IntentFlag.INTENT_FLAG_SMS);
        }
    }

    //重置密码
    public void resetpsw() {
        psw1 = reset_psw__pass.getText().toString();
        psw2 = reset_psw_pass1.getText().toString();
        if (!TextUtils.isEmpty(phoneNumber) && !TextUtils.isEmpty(verity_code)) {
            if (!psw1.equals(psw2)) {
                errTips(err_tips_tv, getString(R.string.psw_should_same));
            } else if (!MeUtil.validatePassword2(psw1)) {
                errTips(err_tips_tv, getString(R.string.password_not_corret));
                // showToastError(R.string.password_null);
            } else if (!MeUtil.validatePassword2(psw1)) {
                errTips(err_tips_tv, getString(R.string.password_not_corret));
                //showToastError(R.string.password_null);
            } else if (!NetworkUtils.isOnline()) {
                errTips(err_tips_tv, getString(R.string.request_failed));
            } else if (!CheckPWD.EvalPWD(psw1)) {
                showPasswordDialog(CWSys.getSharedLong(EConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "", EApplication.BRAND_ID + "", phoneNumber, verity_code, psw1, psw2);
            } else {
                reSetPassword(CWSys.getSharedLong(EConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "", EApplication.BRAND_ID + "", phoneNumber, verity_code, psw1, psw2);
            }

        }
    }

    /**
     * 重置密码
     *
     * @param userId
     * @param business_id
     * @param mobile
     * @param verify_codeBefor
     * @param passwordBefor
     * @param confirmPasswordBefor
     */
    public void reSetPassword(final String userId, String business_id, String mobile, String verify_codeBefor, String passwordBefor, final String confirmPasswordBefor) {
        final String verify_code = AESCBCUtil.encrypt(verify_codeBefor, AESCBCUtil.AESCBC_HEX);
        final String password = AESCBCUtil.encrypt(passwordBefor, AESCBCUtil.AESCBC_HEX);
        final String confirmPassword = AESCBCUtil.encrypt(confirmPasswordBefor, AESCBCUtil.AESCBC_HEX);
        MeDao.getInstance().reSetPSW(business_id, mobile, verify_code, password, confirmPassword, new BaseCallBack() {

            @Override
            public void failed(int errorCode, Object data) {
                errTips(err_tips_tv, String.valueOf(data));
            }

            @Override
            public void failed(Object data) {
                if (data instanceof NoConnectionError) {
                    errTips(err_tips_tv, getString(R.string.connect_disable));

                } else if (data instanceof TimeoutError) {
                    errTips(err_tips_tv, getString(R.string.connect_timeout));

                } else {
                    errTips(err_tips_tv, getString(R.string.unknown_error));
                }
            }

            @Override
            public void success(Object data) {
                Boolean b = (Boolean) data;
                if (b) {
                    SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                            new BaseCallBack() {
                                @Override
                                public void success(Object data) {

                                    List<UserAccountInfo> userAccountList;
                                    userAccountList = (ArrayList<UserAccountInfo>) data;

                                    if (null != userAccountList && userAccountList.size() > 0) {
                                        for (int i = 0; i < userAccountList.size(); i++) {
                                            if (String.valueOf(userAccountList.get(i).getUserId()).equals(userId)) {
                                                userAccountList.get(i).setUserPwd(confirmPassword);
                                                break;
                                            }
                                        }

                                        SerializableManager.getInstance().serialize(
                                                SerializableManager.SerializeKey.SHARE_KEY_USER_ACCOUNT_LIST,
                                                (Serializable) userAccountList, false);
                                    }
                                }

                                @Override
                                public void failed(int errorCode, Object data) {

                                }

                                @Override
                                public void failed(Object data) {

                                }
                            }, false);

                    errTips(err_tips_tv, "密码重置成功！");
                    mHander.sendEmptyMessageDelayed(JIMPTOREGIST, 1200);
                }
            }
        });
    }

    /**
     * 错误提示动画
     *
     * @param view
     */
    private void errTips(final View view, String tips) {
        err_tips_tv.setText(tips);
        err_tips_tv.setVisibility(View.VISIBLE);
        mHander.sendEmptyMessageDelayed(TIPS_GONE, 3000);
    }

    private CWDialog cWPasswordDialog;

    /**
     * 密码简单提示
     */
    private void showPasswordDialog(final String userId, final String business_id, final String mobile, final String verify_codeBefor, final String passwordBefor, final String confirmPasswordBefor) {
        String msgTips = getString(R.string.dialog_passwore_tips);
        if (cWPasswordDialog != null && cWPasswordDialog.isShowing()) {
            cWPasswordDialog.dismiss();
        }
        cWPasswordDialog = new CWDialog(this);
        cWPasswordDialog.setMessagWidePadding(msgTips).setPositiveButton("继续", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cWPasswordDialog.dismiss();
                reSetPassword(CWSys.getSharedLong(EConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "", EApplication.BRAND_ID + "", phoneNumber, verity_code, psw1, psw2);
            }
        }).setNegativeButton("重新设置", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                cWPasswordDialog.dismiss();
            }
        }).setNegativeButtonTextColor(com.ciwong.mobilelib.R.color.color_light_green).show();

        cWPasswordDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cWPasswordDialog.dismiss();
            }
        });
    }
}
